package tushare

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strconv"
	"strings"
	"time"
)

// Income 获取上市公司财务利润表数据
func (api *TuShare) Income(params map[string]string, fields []string) (*APIResponse, error) {
	// Check params
	_, hasTsCode := params["ts_code"]
	if !hasTsCode {
		return nil, fmt.Errorf("ts_code is a required argument")
	}

	body := map[string]interface{}{
		"api_name": "income",
		"token":    api.token,
		"params":   params,
		"fields":   fields,
	}

	return api.postData(body)

}

// BalanceSheet 获取上市公司资产负债表
func (api *TuShare) BalanceSheet(params map[string]string, fields []string) (*APIResponse, error) {
	// Check params
	_, hasTsCode := params["ts_code"]
	if !hasTsCode {
		return nil, fmt.Errorf("ts_code is a required argument")
	}

	body := map[string]interface{}{
		"api_name": "balancesheet",
		"token":    api.token,
		"params":   params,
		"fields":   fields,
	}

	return api.postData(body)
}

// CashFlow 获取上市公司现金流量表
func (api *TuShare) CashFlow(params map[string]string, fields []string) (*APIResponse, error) {
	// Check params
	_, hasTsCode := params["ts_code"]
	if !hasTsCode {
		return nil, fmt.Errorf("ts_code is a required argument")
	}

	body := map[string]interface{}{
		"api_name": "cashflow",
		"token":    api.token,
		"params":   params,
		"fields":   fields,
	}

	return api.postData(body)
}

// Forecast 获取业绩预告数据
func (api *TuShare) Forecast(params map[string]string, fields []string) (*APIResponse, error) {
	// Check param
	_, hasTsCode := params["ts_code"]
	_, hasAnnDate := params["ann_date"]

	// ts_code & ann_date required
	if (!hasTsCode && !hasAnnDate) || (hasTsCode && hasAnnDate) {
		return nil, fmt.Errorf("Need one argument ts_code or ann_date")
	}

	body := map[string]interface{}{
		"api_name": "forecast",
		"token":    api.token,
		"params":   params,
		"fields":   fields,
	}

	return api.postData(body)
}

// Dividend 分红送股数据
func (api *TuShare) Dividend(params map[string]string, fields []string) (*APIResponse, error) {

	body := map[string]interface{}{
		"api_name": "dividend",
		"token":    api.token,
		"params":   params,
		"fields":   fields,
	}

	return api.postData(body)
}

// Express 获取上市公司业绩快报
func (api *TuShare) Express(params map[string]string, fields []string) (*APIResponse, error) {
	// Check params
	_, hasTsCode := params["ts_code"]
	if !hasTsCode {
		return nil, fmt.Errorf("ts_code is a required argument")
	}

	body := map[string]interface{}{
		"api_name": "express",
		"token":    api.token,
		"params":   params,
		"fields":   fields,
	}

	return api.postData(body)
}

// FinaIndicator 获取上市公司财务指标数据
func (api *TuShare) FinaIndicator(params map[string]string, fields []string) (*APIResponse, error) {
	// Check params
	_, hasTsCode := params["ts_code"]
	if !hasTsCode {
		return nil, fmt.Errorf("ts_code is a required argument")
	}

	body := map[string]interface{}{
		"api_name": "fina_indicator",
		"token":    api.token,
		"params":   params,
		"fields":   fields,
	}

	return api.postData(body)
}

// StockFinaIndicator 获取财务指标, 传股票代码和报告期
func (api *TuShare) StockFinaIndicator(symbol string) (*APIResponse, error) {
	// url := "http://10.0.0.88:31023/api/public/stock_financial_analysis_indicator_em" + "?symbol=" + symbol + "&indicator=%E6%8C%89%E6%8A%A5%E5%91%8A%E6%9C%9F"
	url := "http://127.0.0.1:8080/api/public/stock_financial_analysis_indicator_em" + "?symbol=" + symbol + "&indicator=%E6%8C%89%E6%8A%A5%E5%91%8A%E6%9C%9F"
	resp, err := http.Get(url)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	// 开始解析response body
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	jsonData := make([]sFinanceInd, 0)
	err = json.Unmarshal(body, &jsonData)
	if err != nil {
		return nil, err
	}
	ar := APIResponse{
		Code:      200,
		Msg:       "success",
		RequestID: "123",
	}
	ar.Data.Fields = []string{"SECUCODE", "REPORT_DATE", "EPSJB", "EPSKCJB", "BPS", "MGJYXJJE", "PARENTNETPROFIT", "KCFJCXSYJLR", "TOTALOPERATEREVETZ", "PARENTNETPROFITTZ", "KCFJCXSYJLRTZ", "ROEJQ", "ROEKCJQ", "ZZCJLL", "XSJLL", "XSMLL", "ZCFZL"}
	ar.Data.Items = make([][]interface{}, 0)
	now := time.Now()
	yr := now.Year()
	lastYr := strconv.Itoa(yr - 1)
	cYr := strconv.Itoa(yr)
	for _, v := range jsonData {
		// 获取最新一条财务指标
		if strings.HasPrefix(v.RDate, lastYr) || strings.HasPrefix(v.RDate, cYr) {
			ar.Data.Items = append(ar.Data.Items, []interface{}{v.ScCode, v.RDate, v.Epsjb, v.Epskcjb, v.Bps, v.Mgjyxjje, v.Parentnetprofit, v.Kcfjcxsyjlr, v.Totaloperaterevetz, v.Parentnetprofittz, v.Kcfjcxsyjlrtz, v.Roejq, v.Roekcjq, v.Zzcjll, v.Xsjll, v.Xsmll, v.Zcfzl})
			break
		}
	}
	return &ar, nil

}

// FinaAudit 获取上市公司定期财务审计意见数据
func (api *TuShare) FinaAudit(params map[string]string, fields []string) (*APIResponse, error) {
	// Check params
	_, hasTsCode := params["ts_code"]
	if !hasTsCode {
		return nil, fmt.Errorf("ts_code is a required argument")
	}

	body := map[string]interface{}{
		"api_name": "fina_audit",
		"token":    api.token,
		"params":   params,
		"fields":   fields,
	}

	return api.postData(body)
}

// FinaMainbz 获得上市公司主营业务构成，分地区和产品两种方式
func (api *TuShare) FinaMainbz(params map[string]string, fields []string) (*APIResponse, error) {
	// Check params
	_, hasTsCode := params["ts_code"]
	if !hasTsCode {
		return nil, fmt.Errorf("ts_code is a required argument")
	}

	body := map[string]interface{}{
		"api_name": "fina_mainbz",
		"token":    api.token,
		"params":   params,
		"fields":   fields,
	}

	return api.postData(body)
}

// DisclosureDate 获取财报披露计划日期
func (api *TuShare) DisclosureDate(params map[string]string, fields []string) (*APIResponse, error) {

	body := map[string]interface{}{
		"api_name": "disclosure_date",
		"token":    api.token,
		"params":   params,
		"fields":   fields,
	}

	return api.postData(body)
}

type sFinanceInd struct {
	ScCode             string  `json:"SECUCODE"`           // 代码
	RDate              string  `json:"REPORT_DATE"`        // 报告期
	Epsjb              float64 `json:"EPSJB"`              // 基本每股收益
	Epskcjb            float64 `json:"EPSKCJB"`            // 扣非每股收益
	Bps                float64 `json:"BPS"`                // 每股净资产
	Mgjyxjje           float64 `json:"MGJYXJJE"`           // 每股经营现金流
	Parentnetprofit    float64 `json:"PARENTNETPROFIT"`    // 净利润
	Kcfjcxsyjlr        float64 `json:"KCFJCXSYJLR"`        // 扣非净利润
	Totaloperaterevetz float64 `json:"TOTALOPERATEREVETZ"` // 营业总收入同比增长率
	Parentnetprofittz  float64 `json:"PARENTNETPROFITTZ"`  // 净利润同比增长率
	Kcfjcxsyjlrtz      float64 `json:"KCFJCXSYJLRTZ"`      // 扣非净利润同比增长率
	Roejq              float64 `json:"ROEJQ"`              // 净资产收益率
	Roekcjq            float64 `json:"ROEKCJQ"`            // 扣非净资产收益率
	Zzcjll             float64 `json:"ZZCJLL"`             // 总资产收益率
	Xsjll              float64 `json:"XSJLL"`              // 销售净利率
	Xsmll              float64 `json:"XSMLL"`              // 销售毛利率
	Zcfzl              float64 `json:"ZCFZL"`              // 资产负债率
}
